use std::sync::Arc;

use im::{vector, Vector};

use crate::{node::Node, types::ContentEnum};

/**
 * 顶级 Fragment默认只有数组 片段
 * @property content    节点数组
 * @author string<348040933@qq.com>
 */

#[derive(Debug, Clone, PartialEq)]
pub struct Fragment {
    pub content: Vector<Arc<Node>>,
}

impl Fragment {
    pub fn from(content: ContentEnum) -> Self {
        match content {
            ContentEnum::Fragment(fragment) => {
                return fragment;
            }
            ContentEnum::Node(node) => {
                return Fragment {
                    content: vector!(node),
                };
            }
            ContentEnum::Nodes(vec) => {
                return Fragment {
                    content: vec.into(),
                };
            }
            ContentEnum::None => {
                return Fragment::empty();
            }
        }
    }
    pub fn empty() -> Self {
        Fragment { content: vector![] }
    }

    pub fn append(&self, other: Fragment) -> Fragment {
        let mut content = self.content.clone();
        content.extend(other.content);
        Fragment { content }
    }

    pub fn node_at(&self, id: &String) -> Option<Node> {
        for node in self.content.iter() {
            if node.id == *id {
                return Some(node.as_ref().clone());
            } else {
                return node.node_at(id);
            }
        }
        None
    }
    pub fn child_count(&self) -> usize {
        self.content.len()
    }
}
